package com.xindaoapp.happypet.ui;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.utils.Constants;

/**
 * 引用视频，发帖页面
 * 
 * @author xindaoapp
 * 
 */
public class QuoteVideoActivity extends BaseActivity implements OnClickListener {

    public enum VIDEO_TYPE {
        TUDOU, YOUKU
    }

    private WebView web;
    // private ProgressBar progressBar;
    private View vSelectVideo;

    private int mVideoType;

    private String mVideoUrl;
    private String mVideoImageUrl = "";
    private String mVideoName;
    private String mVideoDescription;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_quote_video;
    }

    @Override
    protected void initViews() {
        super.initViews();
        // Here is all of our WebView Components
        web = (WebView) findViewById(R.id.webview);
        web.setBackgroundColor(Color.parseColor("#ffffff"));
        web.setWebViewClient(new myWebClient());
        // progressBar = (ProgressBar) findViewById(R.id.progressbar);
        web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int progress) {
                // progressBar.setProgress(progress);
            }
        });
        WebSettings websettings = web.getSettings();
        // websettings.setBuiltInZoomControls(true);
        websettings.setUseWideViewPort(true);
        websettings.setJavaScriptEnabled(true);
        websettings.setAllowFileAccess(true);
        websettings.setDomStorageEnabled(true);
        websettings.setLoadWithOverviewMode(true);
        // websettings.setUserAgentString("Android");
        websettings.setAppCacheEnabled(true);
        websettings.setSavePassword(true);

        // Load the URL you want to load
        mVideoType = getIntent().getIntExtra(Constants.KEY_VIDEO_TYPE, VIDEO_TYPE.TUDOU.ordinal());
        if (mVideoType == VIDEO_TYPE.TUDOU.ordinal()) {
            web.loadUrl("http://m.56.com/");
            setTopBarTitle("56视频");
        } else if (mVideoType == VIDEO_TYPE.YOUKU.ordinal()) {
            web.loadUrl("http://www.youku.com");
            setTopBarTitle("优酷");
        }
        // Also can be used like this
        // web.loadUrl("http://www.url.com"");
        vSelectVideo = findViewById(R.id.select_video);
    }

    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                finish();
            }
        };
    }

    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        vSelectVideo.setOnClickListener(this);
    }

    public class myWebClient extends WebViewClient {

        @Override
        public void onPageStarted(final WebView view, final String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            // Show the progress bar when page starts loading
            // progressBar.setVisibility(View.VISIBLE);

            if (mVideoType == VIDEO_TYPE.TUDOU.ordinal()) {
                if (url.endsWith(".html")) {
                    parse56Video(url);
                } else {
                    vSelectVideo.setEnabled(false);
                }
            } else if (mVideoType == VIDEO_TYPE.YOUKU.ordinal()) {
                if (url.startsWith("http://v.youku.com/v_show/id")) {
                    parseYoukuVideo(url);
                } else {
                    vSelectVideo.setEnabled(false);
                }
            }

        }

        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, String url) {
            // Here we allow other links to be clicked and opened
            view.loadUrl(url);
            // Make sure the progress bar is visable
            // progressBar.setVisibility(View.VISIBLE);
            return true;
        }

        public void onProgressChanged(WebView view, int progress) {
            // Here is where the page is loading
            // progressBar.setProgress(progress);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description,
                String failingUrl) {
            // Here you can place code to execute when there is a error, like No
            // data or a bad URL
        };

        @Override
        public void onPageFinished(WebView view, final String url) {
            super.onPageFinished(view, url);

            // Here we disable the progress bar when the page finishs loading
            // progressBar.setVisibility(View.GONE);
        }
    }

    private void parse56Video(final String url) {
        mVideoUrl = url;
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Document document = Jsoup.parse(new URL(url), 10000);

                    Elements links = document.select("link");

                    for (Element element : links) {
                        if (element.attr("rel").equals("apple-touch-icon")) {
                            mVideoImageUrl = element.attr("href");
                            break;
                        }
                    }

                    Elements titles = document.select("title");

                    for (Element element : titles) {
                        mVideoName = element.text();
                    }

                    Elements metas = document.select("meta");

                    for (Element element : metas) {
                        if (element.attr("name").equals("description")) {
                            mVideoDescription = element.attr("content");
                            break;
                        }
                    }
                    HappyPetApplication.mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            vSelectVideo.setEnabled(true);
                        }
                    });
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();;
    }

    private void parseYoukuVideo(final String url) {
        mVideoUrl = url;
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Document document = Jsoup.parse(new URL(url), 10000);

                    // 图片封面通过截取字符串
                    String result = document.toString();

                    int start = result.indexOf("imageUrl=");
                    if (start > -1) {
                        int end = result.indexOf("&", start);
                        mVideoImageUrl = result.substring(start + "imageUrl=".length(), end);
                    }

                    // 防止网页内容可能没有封面地址的情况，如果为空，则不处理
                    if (TextUtils.isEmpty(mVideoImageUrl)) {
                        return;
                    }

                    Elements titles = document.select("title");

                    for (Element element : titles) {
                        mVideoName = element.text();
                    }

                    Elements metas = document.select("meta");

                    for (Element element : metas) {
                        if (element.attr("name").equals("description")) {
                            mVideoDescription = element.attr("content");
                            break;
                        }
                    }
                    HappyPetApplication.mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            vSelectVideo.setEnabled(true);
                        }
                    });
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (web.canGoBack()) {
                web.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        web.removeAllViews();
        web.destroy();
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.select_video:
                Intent data = new Intent();
                data.putExtra(Constants.KEY_VIDEO_URL, mVideoUrl);
                data.putExtra(Constants.KEY_VIDEO_NAME, mVideoName);
                data.putExtra(Constants.KEY_VIDEO_IMAGE_URL, mVideoImageUrl);
                data.putExtra(Constants.KEY_VIDEO_DESCRIPTION, mVideoDescription);
                setResult(RESULT_OK, data);
                finish();
                break;

            default:
                break;
        }
    }
}
